package org.dei.perla.sys.console;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

import org.dei.perla.sys.core.AgentRegistry;
import org.dei.perla.sys.core.AgentState;
import org.dei.perla.sys.core.DefaultAgent;
import org.dei.perla.sys.core.PerlaRuntime;

/**
 * Classe per implementare la console
 * @author Diego
 */
public class ConsoleServer extends DefaultAgent<Object, String> {
	
	int port;
	private static final int DEFAULT_PORT = 14567;
	
	
	public ConsoleServer(String parName) {
		super(parName);
	 	PerlaRuntime runtime = PerlaRuntime.getDefaultRuntime();
	 	if(runtime.containsKey("CONSOLE_SERVER_PORT"))
	 		this.port = new Integer(runtime.getProperty("CONSOLE_SERVER_PORT"));
	 	else
	 		this.port = DEFAULT_PORT;
	}

	
	private ArrayList<Socket> clentList = new ArrayList<Socket>();
	
	@Override
	public ArrayList<String[]> inspect() {
		ArrayList<String[]> retValue = new ArrayList<String[]>();
		String head[] = {"Client java object", "Client IP"};
		retValue.add(head);
		for (Iterator<Socket> iterator = clentList.iterator(); iterator.hasNext();) {
			Socket client = (Socket) iterator.next();
			String[] element = {client.toString(), client.getInetAddress().toString()};
			retValue.add(element);
		}
		return retValue;
	}

	@Override
	protected void loop() throws Exception {
		System.out.println("SERVER: creating socket\n");
		ServerSocket tServerSocket = new ServerSocket(port);
		System.out.println("ciclo\n");
		while (true) {
			System.out.println("SERVER: accepting.... \n");
			Socket tClientSocket = tServerSocket.accept();
			this.clentList.add(tClientSocket);
			System.out.println("SERVER: accepted, creo thread \n");
			new ServerThread(tClientSocket, this.getOutputPipe()).run();
		}
	}

	@Override
	public void respawn() {
		AgentState state =  AgentRegistry.getAgentStatus(this);
		switch(state) {
			case DEAD:{
				new Thread(this).start();
			}
			case STOPPED:
			case RUNNING:
			default:
				break;
		}
	}
}
